package com.qf.service.impl;

import com.qf.dao.AddressDao;
import com.qf.dao.CartDao;
import com.qf.dao.OrderDao;
import com.qf.dao.impl.AddressDaoImpl;
import com.qf.dao.impl.CartDaoImpl;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.service.OrderService;
import com.qf.pojo.CartDto;
import com.qf.pojo.TbGoods;
import com.qf.pojo.TbOrder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Create by 周志豪 on 2022/8/21  10:45
 *
 * @authoe 周志豪
 * @veision 1.0
 * //TODO  想好了再去做
 * @since 1.0
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();

    private CartDao cartDao = new CartDaoImpl();

    private AddressDao addressDao = new AddressDaoImpl();

    @Override
    public Map createOrder(Long userId, Long addressId, CartDto cartDto) {

        long sum = 0;
        //遍历商品
        for (int i = 0; i < cartDto.getGoodsList().size(); i++) {
            //拿到每一件商品的价格和数量进行计算
            sum += cartDto.getGoodsList().get(i).getPrice() * cartDto.getNums()[i];
        }
        //1  生成一个订单的id,然后加上地址的id,用户的id,计算出商品的总价格,然后将数据插入到订单表中
        String orderId = UUID.randomUUID().toString().replace("-", "");
        orderDao.addOrder(orderId, userId, addressId, sum);
        //利用上面生成的订单的id,和购物车中每一条数据,生成每一条订单详情单数据,也就是订单和商品之间的中间表的数据,插入到中间表中
        for (int i = 0; i < cartDto.getGoodsList().size(); i++) {
            //将每一条商品的信息插入到数据库
            TbGoods tbGoods = cartDto.getGoodsList().get(i);
            orderDao.addOrderDetail(orderId,tbGoods.getKzid(),cartDto.getNums()[i],tbGoods.getPrice()*cartDto.getNums()[i]);
        }
        //返回结果
        //清理购物车
        cartDao.clearCart(userId);
        //返回结果的map
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", orderId);
        resultMap.put("money", sum);
        return resultMap;
    }

    @Override
    public int updateOrderStaus(String oid, String status) {
        return orderDao.updateOrderStaus(oid, status);
    }

    @Override
    public List<TbOrder> findByUserId(Long userId) {
        //先查询订单
        List<TbOrder> orderList = orderDao.findByUserId(userId);
        //查询每个订单关联的地址
        orderList.forEach(tbOrder -> {
//            //获取到每一地址的id
//            Long aid = tbOrder.getAid();
//            //获取到地址
//            TbAddress address = addressDao.findById(aid);
//            tbOrder.setAddress(address);
            tbOrder.setAddress(addressDao.findById(tbOrder.getAid()));
        });

        return orderList;
    }
}
